// 保存配置到Chrome存储
function saveSettings() {
  const enableFilter = document.getElementById('enableFilter').checked;
  const minImages = parseInt(document.getElementById('minImages').value) || 1;

  chrome.storage.sync.set({
    enableFilter,
    minImages,
  }, () => {
    // 通知content script配置已更新
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          type: 'SETTINGS_UPDATED',
          settings: { enableFilter, minImages }
        });
      }
    });
  });
}

// 从Chrome存储加载配置
function loadSettings() {
  chrome.storage.sync.get({
    enableFilter: true,
    minImages: 1,
    filteredCount: 0
  }, (items) => {
    document.getElementById('enableFilter').checked = items.enableFilter;
    document.getElementById('minImages').value = items.minImages;
    document.getElementById('status').textContent = `已过滤 ${items.filteredCount} 条回答`;
  });
}

// 监听配置变化
document.getElementById('enableFilter').addEventListener('change', saveSettings);
document.getElementById('minImages').addEventListener('change', saveSettings);

// 初始化加载配置
document.addEventListener('DOMContentLoaded', loadSettings);

// 监听来自content script的消息更新
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'UPDATE_FILTERED_COUNT') {
    document.getElementById('status').textContent = `已过滤 ${message.count} 条回答`;
    chrome.storage.sync.set({ filteredCount: message.count });
  }
});